package pgschedule

import (
	"flare-admin/db/sqlc/cluster"
	"flare-admin/http/model"
	"flare-admin/http/request"
	"time"

	"github.com/jackc/pgx/v5/pgtype"
)

func ScheduleRecord2AddRecordParam(recordRequest *request.SchedulingRecordRequest) (cluster.AddPodGroupRecordParams, error) {
	if recordRequest == nil {
		return cluster.AddPodGroupRecordParams{}, nil
	}
	commitTime, err := time.Parse(time.RFC3339, recordRequest.CommitTime)
	if err != nil {
		return cluster.AddPodGroupRecordParams{}, err
	}
	ctz := pgtype.Timestamptz{}
	err = ctz.Scan(commitTime)
	if err != nil {
		return cluster.AddPodGroupRecordParams{}, err
	}
	return cluster.AddPodGroupRecordParams{
		Name:         recordRequest.Name,
		Uid:          recordRequest.UID,
		Namespace:    recordRequest.Namespace,
		Clusterid:    recordRequest.ClusterID,
		Committime:   ctz,
		Dependencies: []byte(recordRequest.Dependencies),
	}, nil
}

func ScheduleRecord2UpdateRecordParam(recordRequest *request.SchedulingRecordRequest) (cluster.UpdatePodGroupRecordParams, error) {
	if recordRequest == nil {
		return cluster.UpdatePodGroupRecordParams{}, nil
	}
	updateAt, err := time.Parse(time.RFC3339, recordRequest.UpdateAt)
	if err != nil {
		return cluster.UpdatePodGroupRecordParams{}, err
	}
	updateAtTz := pgtype.Timestamptz{}
	err = updateAtTz.Scan(updateAt)
	if err != nil {
		return cluster.UpdatePodGroupRecordParams{}, err
	}
	return cluster.UpdatePodGroupRecordParams{
		Name:        recordRequest.Name,
		Namespace:   recordRequest.Namespace,
		Clusterid:   recordRequest.ClusterID,
		ScheduleRes: []byte(recordRequest.ScheduledRes),
		LatencyInfo: []byte(recordRequest.LatencyInfo),
		UpdateTime:  updateAtTz,
		Uid:         recordRequest.UID,
	}, nil
}

func DBRecord2ScheduleRecordModel(record cluster.SelectPodGroupRecordByClusterIDRow) (res model.ScheduleRecord) {
	res.Name = record.Name
	res.Namespace = record.Namespace
	res.Uid = record.Uid
	res.Status = record.Status
	res.CreateTime = record.CommitTime.Time.Format(time.RFC3339)
	return
}
